<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/js.cookie.js"></script>
    <script>
        //模拟数据,从后端拿数据
        var Data = [
            { id: 1, name: "飞机", price: 289 },
            { id: 2, name: "坦克", price: 389 },
            { id: 3, name: "单车", price: 589 },
            { id: 4, name: "汽车", price: 889 },
            { id: 5, name: "摩托车", price: 989 },
            { id: 6, name: "法拉第", price: 1999 }
        ]
    </script>
</head>

<body>



    <ul id="list">
        <li>
            <span></span>
            <a href=""></a>
        </li>
    </ul>




    <a href="./购物车.html">查看购物车</a>

    <script>
        var oList = document.querySelector('#list');
        var str = ``;
        Data.forEach(function (item, index) {
            str += `    
                <li>
                    <span>
                        编号:${item.id}
                        名称:${item.name}
                        价格:${item.price}
                    </span>    
                    <a data-id=${item.id} href='javascript:void(0)'>加入购物车</a>
                </li>
            `
        })

        oList.innerHTML = str;
        //事件委托
        oList.addEventListener("click", function (evt) {
            var e = evt || window.event;
            var ele = e.target || e.srcElement;
            if (ele.nodeName != 'A') {
                return;
            }
            var id = ele.getAttribute("data-id");
            //console.log(id);
            //根据id得到上面的具体信息 
            var current = Data.filter(function (item, index) {
                return item.id == id
            })[0]

            //console.log(current);
            //加入购物车 
            //1.读取本地cookie所有商品信息
            //把硬盘上的数据,读取到了内存条中
            var oCarts = JSON.parse(Cookies.get("carts") || '[]');
            //2. 拿cookie商品的信息与 当前购物的数据,进行比较
            var flag = true;//默认是没有购买过
            for (var i = 0; i < oCarts.length; i++) {
                // 如果存在,就修改数量
                if (oCarts[i].id == current.id) {
                    oCarts[i].number = Number(oCarts[i].number) + 1;
                    flag = false; //购买过,修改数量
                    break;
                }
            }

            if (flag) {
                // 如果不存在, 当前的商品,添加数量1,保存到cookie的列表
                current.number = 1;
                oCarts.push(current); //oCarts 内存条的数据,发生了变化
            }

            //3. 把cookie列表 保存到本地数据
            Cookies.set("carts", oCarts, { expires: 10 });

            alert("加入购物车成功!")
        })

    </script>
</body>

</html>